package service.impl;

import dao.OrderMapper;
import entity.Order;
import org.apache.ibatis.session.SqlSession;
import service.OrderService;
import utils.MyBatisUtils;
import java.util.List;

public class OrderServiceImpl implements OrderService {

    @Override
    public Order getById(Long id) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        try {
            OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
            return mapper.selectById(id);
        } finally {
            sqlSession.close(); // 释放资源
        }
    }

    @Override
    public List<Order> getByUserId(Long userId) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        try {
            OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
            return mapper.selectByUserId(userId);
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public Order getByOrderNumber(String orderNumber) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        try {
            OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
            return mapper.selectByOrderNumber(orderNumber);
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public void add(Order order) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        try {
            OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
            mapper.insert(order);
            sqlSession.commit(); // 提交事务
        } catch (Exception e) {
            sqlSession.rollback(); // 事务回滚
            throw new RuntimeException("新增订单失败", e);
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public int update(Order order) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        try {
            OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
            int rows = mapper.updateById(order);
            sqlSession.commit();
            return rows;
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException("更新订单失败", e);
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public int delete(Long id) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        try {
            OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
            int rows = mapper.deleteById(id);
            sqlSession.commit();
            return rows;
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException("删除订单失败", e);
        } finally {
            sqlSession.close();
        }
    }
}